import { ref, computed, Ref } from 'vue';
import { PageInfoRequest } from '/#/common';
import { messageFn } from '/@/store/utils';
import { AxiosCanceler } from '/@/utils/http/axios/axiosCancel';


interface Options<U> {
  api: Function;
  isPoll?: boolean;
  form?: U;
  setData?: Fn;
  scroll?: Element | null;
  immediate?: boolean;
}

export const useTablePage = <T = any, U = any>({
  api,
  isPoll = false,
  form,
  setData,
  scroll,
  immediate = true,
}: Options<U>) => {
  const loading = ref<boolean>(false);
  const page_no = ref<number>(1);
  const page_size = ref<number>(10);
  // 缓存旧的pageSize
  const old_page_size = ref<number>(10);
  const total = ref<number>(0);
  const list = ref<T[]>([]) as Ref<T[]>;
  const searchForm = ref<U>();
  const pageSizeOptions = ref<any>(['10', '50', '80', '100'])
  if (form) {
    searchForm.value = form as U;
  }
  const pagination = computed<any>(() => {
    return {
      current: page_no.value,
      pageSize: page_size.value,
      total: total.value,
      showSizeChanger: true,
      showQuickJumper: true,
      pageSizeOptions: pageSizeOptions.value,
      showTotal: (total) => `共 ${total} 条数据`,
      style: {
        position: 'relative',
        right: '50%',
        transform: 'translate(50%)',
      },
    };
  });

  // 轮询查询Api
  const pollApi = async (pages: number) => {
    if (page_no.value < pages) {
      page_no.value++
      await hanldeQueryPage()
    } else {
      loading.value = false;
    }
  }

  const setResult = (res: any) => {
    let resultData: T[] = []
    let pages = 0
    total.value = 0
    
    if (res.page_no) {
      resultData = res.data;
      pages = res.total_pages || 0;
      total.value = res.total || 0;
    } else if (res.data.page_no) {
      resultData = res.data.list || [];
      total.value = res.data.total || 0;
      pages = res.data.pages || 0;
    } else if (res.data.page_result.page_no ||  res.data.page_result.pageNo) {
      resultData = res.data.page_result.list || [];
      total.value = res.data.page_result.total || 0;
      pages = Math.ceil(res.data.page_result.total / page_size.value);
    }
    
    return { resultData, pages }
  }

  // 获取数据
  const hanldeQueryPage = async () => {
    if (scroll) {
      scroll.scrollTo(0, 0);
    }
    // 旧的不等于新的pagesize
    if (old_page_size.value !== page_size.value) {
      page_no.value = 1
      old_page_size.value = page_size.value
    }

    loading.value = true;
    const params: PageInfoRequest & U = {
      page_no: page_no.value,
      page_size: page_size.value,
      ...(searchForm.value as U),
    };

    // 如果是第一页，就清除数据，否则会被前面请求的数据进行push
    if (page_no.value === 1 && isPoll) {
      const axiosCanceler = new AxiosCanceler();
      axiosCanceler?.removeAllPending()
      list.value = []
    }
    
    try {
      const res = await api(params);
      if (res.code === 0) {
        // 对数据进行操作
        if (setData) {
          setData(res);
          return
        } 
        
        const { resultData, pages } = setResult(res)

        if (isPoll) {
          list.value.push(...resultData)
          await pollApi(pages)
          
        } else {
          list.value = resultData
        }

      } else {
        messageFn('error', res.msg);
        loading.value = false;
        throw new Error('轮询报错中断轮询')
      }
    } catch {
      loading.value = false;
    } finally {
      if (!isPoll) {
        loading.value = false;
      }
    }
  };

  if (immediate) {
    hanldeQueryPage();
  }

  // 删除的是否是最后一项，是就返回上一页
  const isPrePage = () => {
    let totalPage = Math.ceil((total.value - 1) / page_size.value);
    let currentPage = page_no.value > totalPage ? totalPage : page_no.value;
    page_no.value = currentPage < 1 ? 1 : currentPage;
    hanldeQueryPage();
  };

  // watch(() => page_size.value, () => {
  //   page_no.value = 1
  //   console.log('1', 111111);
    
  // })

  return {
    loading,
    searchForm,
    page_no,
    page_size,
    pageSizeOptions,
    total,
    list,
    pagination,
    hanldeQueryPage,
    isPrePage,
  };
};
